package cn.dao.impl;


import cn.dao.AccountDao;
import cn.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class AccountDaoImpl implements AccountDao {
    /**
     * 定义JdbcTemplate属性并实现其set方法(依赖注入时使用)
     */
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 增删改全用 update 方法
     */
    public Integer addAccount(Account account) {
        String sql = "insert into t_account(name,money) values (?,?) ";
        Object[] obj = new Object[]{account.getName(), account.getMoney()};
        int num = jdbcTemplate.update(sql, obj);
        return num;
    }

    public Integer deleteAccount(Integer id) {
        String sql = "delete from t_account where id=? ";
        Integer num = jdbcTemplate.update(sql, id);
        return num;
    }

    public Integer updateAccount(Account account) {
        String sql = "update t_account set name=? , money=? where id=? ";
        Object[] params = new Object[]{account.getName(), account.getMoney(), account.getId()};
        Integer num = jdbcTemplate.update(sql, params);
        return num;
    }

    public Account findAccountById(Integer id) {
        String sql = "select * from t_account where id=? ";
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        return jdbcTemplate.queryForObject(sql, rowMapper, id);
    }

    public List<Account> findAll() {
        String sql = "select * from t_account ";
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        return jdbcTemplate.query(sql, rowMapper);
    }
}
